package com.example.myprojectoffeixue;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.odps.udf.CodecCheck;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import org.apache.http.entity.StringEntity;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

//本界面是添加场景的界面，修改场景与新建场景的不同点只是修改场景不能改变场景的类型，
// 注意的是界面跳转时要将一些必要的数据传递，当然也可以直接在myapplicatiaon中设置
//每次执行添加设备操作，清空存放数据的map


public class AddCJActivity extends Activity {
    private ArrayList<SheBeiClass> sb;
    private ArrayList<SheBeiClass> sb1;
    private ArrayList<SheBeiClass> sb2;
    MyApplication m;
    private EditText name;
    private TextView tv;
    private ListView lv;
    public static int flag=1;
    private int kinds_flag;
    private int flag1 = 4;
    String scenname;
    Dialog dialog;
    public static String deviceName;
    public static String mac;
    public static String ieee;
    public static String deviceId;
    public static String port;
    public static String status;
    TimePicker tp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_cj);
        m = (MyApplication) getApplication();
        Intent it = getIntent();
        kinds_flag=it.getIntExtra("kinds_flag",-1);
        if (kinds_flag==-1) {
            m.map.clear();
            AddCJActivity.flag=1;
        }else{
           if(kinds_flag==3){
               AddCJActivity.mac=m.cj.mac;
               AddCJActivity.ieee=m.cj.ieee;
               AddCJActivity.port=m.cj.port;
               AddCJActivity.status=m.cj.status;
               AddCJActivity.deviceId=m.cj.deviceId;
               String s1=m.cj.ieee+m.cj.port;
               int x=0;
               for(int i=0;i<m.lsb2.size();i++){
                   String s2=m.lsb2.get(i).ieee+m.lsb2.get(i).port;
                   if(s1.equals(s2)){
                       deviceName=m.lsb2.get(i).deviceName;
                       x=1;
                   }
               }
               if(x==0){
                   deviceName="红外";
               }
           }else if(kinds_flag==4){
               AddCJActivity.mac=m.cj.mac;
               AddCJActivity.ieee=m.cj.ieee;
               AddCJActivity.port=m.cj.port;
               AddCJActivity.status=m.cj.status;
               AddCJActivity.deviceId=m.cj.deviceId;
               String s1=m.cj.ieee+m.cj.port;
               int x=0;
               for(int i=0;i<m.lsb4.size();i++){
                   String s2=m.lsb4.get(i).ieee+m.lsb4.get(i).port;
                   if(s1.equals(s2)){
                       deviceName=m.lsb4.get(i).deviceName;
                       x=1;
                   }
               }

               if(x==0){
                   deviceName="门磁";
               }


           }
            AddCJActivity.flag=kinds_flag;
        }

        sb = new ArrayList<SheBeiClass>();
        sb1 = new ArrayList<SheBeiClass>();
        sb.clear();
        sb1.clear();
        sb.addAll(m.lsb);
       // sb.addAll(m.lsb1);
        sb.addAll(m.lsb3);
        sb.addAll(m.lsb5);
        sb.addAll(m.lsb8);

        for (int i = 0; i < sb.size(); i++) {

            SheBeiClass s = new SheBeiClass();
            s.mac = sb.get(i).mac;
            s.ieee = sb.get(i).ieee;
            s.port = sb.get(i).port;
            s.deviceId = sb.get(i).deviceId;
            s.deviceName = sb.get(i).deviceName;
            s.status = "";
            sb1.add(s);
        }

        name = (EditText) findViewById(R.id.et_addcj);
        name.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
        if (kinds_flag != -1) {
            m.map.clear();
            ArrayList<devices> devices =null;
            if (kinds_flag==1) {
                devices=m.cj.devices;
                name.setText(m.cj.sceneName);
            } else if (kinds_flag==2 ) {
                devices = m.cj.devices;
                name.setText(m.cj.sceneName);
            } else if (kinds_flag==3) {
                devices = m.cj.devices;
                name.setText(m.cj.sceneName);
            }else if(kinds_flag==4){
                devices = m.cj.devices;
                name.setText(m.cj.sceneName);
            }
            for (int i = 0; i < devices.size(); i++) {
                for (int j = 0; j < sb1.size(); j++) {
                    String ieeport = sb1.get(j).ieee + sb1.get(j).port;
                    String ieeport2 = devices.get(i).ieee + devices.get(i).port;
                    if (ieeport.equals(ieeport2)) {
                        if ("00".equals(devices.get(i).status)) {
                            m.map.put(j, 0);
                        } else if ("01".equals(devices.get(i).status)) {
                            m.map.put(j, 1);
                        }
                    }

                }
            }
        }



    }

    @Override
    protected void onStart() {
        info();
        super.onStart();
    }

    public void info() {
        LinearLayout iv = (LinearLayout) findViewById(R.id.iv_mykaiguan);
        iv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                m.map.clear();
                finish();
            }
        });
        m = (MyApplication) getApplication();


        ImageView ivleixing = (ImageView) findViewById(R.id.iv_leixing);
        final TextView tvleixing = (TextView) findViewById(R.id.tv_leixing);

        if (flag == 1) {
            ivleixing.setImageResource(R.drawable.icon_shoudong_kaiqi);
            tvleixing.setText("手动启动");

        } else if (flag == 2) {
            ivleixing.setImageResource(R.drawable.icon_zidongg_kaiqi);
            tvleixing.setText("定时启动");
        } else if (flag == 3) {
            ivleixing.setImageResource(R.drawable.hw2);
            tvleixing.setText(deviceName);

        } else if (flag == 4) {
            ivleixing.setImageResource(R.drawable.mc);
            tvleixing.setText(deviceName);


        }
        if(sb2==null){
        sb2 = new ArrayList<SheBeiClass>();}else{
            sb2.clear();
        }


        LinearLayout leixing = (LinearLayout) findViewById(R.id.cjleixing);
        leixing.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(AddCJActivity.this, CJleiXingActivity.class);
                startActivity(it);
            }
        });
        tv = (TextView) findViewById(R.id.wancheng);

        tv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                scenname = name.getText().toString();
                if ("".equals(scenname)) {
                    ToastUtils.showToast(AddCJActivity.this,"请输入场景名称");
                } else if (m.map.size() == 0) {
                    ToastUtils.showToast(AddCJActivity.this,"请选择设备");
                } else if (kinds_flag==1 && flag != 1) {

                    ToastUtils.showToast(AddCJActivity.this,"与原场景类型不匹配");

                } else if (kinds_flag==2 && flag != 2) {

                    ToastUtils.showToast(AddCJActivity.this,"与原场景类型不匹配");

                } else if (kinds_flag==3 && (flag != 3 && flag != 4)) {

                    ToastUtils.showToast(AddCJActivity.this,"与原场景类型不匹配");
                } else {

                    if (flag == 1) {

                        CJutil c = new CJutil();
                        c.userId = m.userId;
                        c.sceneName = scenname;
                        c.sceneType = 1;
                        c.devices = new ArrayList<devices>();
                        for (int i = 0; i < sb1.size(); i++) {

                            if (m.map.containsKey(i)) {
                                devices d = new devices();
                                d.deviceId = sb1.get(i).deviceId;
                                d.status = sb1.get(i).status;
                                d.ieee = sb1.get(i).ieee;
                                d.port = sb1.get(i).port;
                                d.mac = sb1.get(i).mac;
                                c.devices.add(d);
                            }
                        }
                        if(m.ScenId!=-1){
                            c.sceneId=m.ScenId;
                            String l = JSON.toJSONString(c);
                            updateScene(l);
                        }else{
                        String l = JSON.toJSONString(c);
                        addScene(l);}

                    } else if (flag == 2) {
                        dialog = new Dialog(AddCJActivity.this);
                        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        dialog.setContentView(R.layout.dingshi2);
                        ImageView iv1 = (ImageView) dialog.findViewById(R.id.delete_dingshi);
                        tp = (TimePicker) dialog.findViewById(R.id.timepicker);
                        tp.setIs24HourView(true);
                        iv1.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();

                            }
                        });
                        RadioButton ra = (RadioButton) dialog.findViewById(R.id.radio1_dingshi);
                        RadioButton ra1 = (RadioButton) dialog.findViewById(R.id.radio2_dingshi);

                        ImageView iv3 = (ImageView) dialog.findViewById(R.id.iv_dingshidialog);

                        ra.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                flag1 = 4;

                            }
                        });

                        ra1.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                flag1 = 5;
                            }
                        });
                        Log.d("size", m.map.size() + "");
                        iv3.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Log.d("size", m.map.size() + "");

                                CJutil c = new CJutil();
                                c.userId = m.userId;
                                c.sceneType = 2;
                                c.devices = new ArrayList<devices>();
                                c.sceneName = scenname;
                                if (flag1 == 4) {
                                    c.loopFlag = "0";
                                } else if (flag1 == 5) {
                                    c.loopFlag = "1";
                                }
                                for (int i = 0; i < sb1.size(); i++) {

                                    Log.d("size", m.map.size() + "");

                                    if (m.map.containsKey(i)) {
                                        devices d = new devices();
                                        d.deviceId = sb1.get(i).deviceId;
                                        d.status = sb1.get(i).status;
                                        d.ieee = sb1.get(i).ieee;
                                        d.port = sb1.get(i).port;
                                        d.mac = sb1.get(i).mac;
                                        c.devices.add(d);
                                    }
                                }
                                String hour;
                                String minute;
                                if (tp.getCurrentHour() < 10) {
                                    hour = "0" + tp.getCurrentHour();
                                } else {
                                    hour = "" + tp.getCurrentHour();
                                }

                                if (tp.getCurrentMinute() < 10) {

                                    minute = "0" + tp.getCurrentMinute();
                                } else {
                                    minute = "" + tp.getCurrentMinute();
                                }
                                c.runTime = hour + ":" + minute + ":" + "00";
                                if(m.ScenId!=-1){
                                    c.sceneId=m.ScenId;
                                    String l = JSON.toJSONString(c);
                                    updateScene(l);
                                }else{
                                String l = JSON.toJSONString(c);
                                addScene(l);
                                }


                            }
                        });
                        dialog.show();

                    } else if (flag == 3) {

                        CJutil c = new CJutil();
                        c.devices = new ArrayList<devices>();
                        c.mac = mac;
                        c.userId = m.userId;
                        c.deviceId = deviceId;
                        c.eventStatus = 0;
                        c.ieee = ieee;
                        c.port = port;
                        c.status = AddCJActivity.status;
                        c.sceneType = 3;
                        c.sceneName = scenname;
                        for (int i = 0; i < sb1.size(); i++) {
                            if (m.map.containsKey(i)) {
                                devices d = new devices();
                                d.deviceId = sb1.get(i).deviceId;
                                d.status = sb1.get(i).status;
                                d.ieee = sb1.get(i).ieee;
                                d.port = sb1.get(i).port;
                                d.mac = sb1.get(i).mac;
                                c.devices.add(d);
                            }
                        }
                        if(m.ScenId!=-1){
                            c.sceneId=m.ScenId;
                            String l = JSON.toJSONString(c);
                            updateScene(l);
                        }else{
                            String l = JSON.toJSONString(c);
                            addScene(l);
                        }

                    } else if (flag == 4) {
                        CJutil c = new CJutil();
                        c.devices = new ArrayList<devices>();
                        c.deviceId = deviceId;
                        c.mac = mac;
                        c.userId = m.userId;
                        c.ieee = ieee;
                        c.port = port;
                        c.status = status;
                        c.sceneType = 3;
                        c.eventStatus = 0;
                        c.sceneName = scenname;
                        for (int i = 0; i < sb1.size(); i++) {
                            if (m.map.containsKey(i)) {
                                devices d = new devices();
                                d.deviceId = sb1.get(i).deviceId;
                                d.status = sb1.get(i).status;
                                d.ieee = sb1.get(i).ieee;
                                d.port = sb1.get(i).port;
                                d.mac = sb1.get(i).mac;
                                c.devices.add(d);
                            }
                        }
                        if(m.ScenId!=-1){
                            c.sceneId=m.ScenId;
                            String l = JSON.toJSONString(c);
                            updateScene(l);
                        }else{
                            String l = JSON.toJSONString(c);
                            addScene(l);
                        }
                    }
                }


            }
        });


        for (int i = 0; i < sb1.size(); i++) {
            if (m.map.containsKey(i)) {
                if (0 == m.map.get(i)) {
                    sb1.get(i).status = "00";
                } else if (1 == m.map.get(i)) {
                    sb1.get(i).status = "01";
                }
                sb2.add(sb1.get(i));
            }
            lv = (ListView) findViewById(R.id.lv_addchangjing);
            lv.setAdapter(new CjSbadapter(sb2, AddCJActivity.this));
        }
    }


    public void addshebei(View v) {
        // m.map.clear();
        Intent it = new Intent(AddCJActivity.this, AddCJshebeiActivity.class);
        startActivity(it);
    }

    private void addScene(String s) {
        tv.setClickable(false);
        s = AESUtil.encrypt(s);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(s, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.addScene, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                       ToastUtils.showToast(AddCJActivity.this,"网络错误");
                        tv.setClickable(true);

                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        if (arg0.result != null && !("".equals(arg0.result))) {
                            arg0.result = AESUtil.decrypt(arg0.result);
                            JSONObject jb = JSONObject.parseObject(arg0.result);
                            String msg = jb.getString("msg");
                            int ST = jb.getInteger("sceneType");
                            int SD = jb.getInteger("sceneId");
                            if ("成功".equals(msg)) {
                                if(dialog!=null){
                                    dialog.dismiss();
                                }
                                Startscen(SD,ST);
                            }else{
                                tv.setClickable(true);
                                ToastUtils.showToast(AddCJActivity.this,"服务器错误");
                            }

                        } else {
                            tv.setClickable(true);
                            ToastUtils.showToast(AddCJActivity.this,"服务器错误");

                        }
                    }

                });

    }




    public void updateScene(String s) {
        tv.setClickable(false);
        s = AESUtil.encrypt(s);
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.setHeader("Content-Type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(s, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.updateScene, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        HttpConnection.toastLog("网络异常", AddCJActivity.this);
                        tv.setClickable(true);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        if (arg0.result != null && !("".equals(arg0.result))) {
                            arg0.result = AESUtil.decrypt(arg0.result);
                            JSONObject jb = JSONObject.parseObject(arg0.result);
                            String msg = jb.getString("msg");
                            int ST = jb.getInteger("sceneType");
                            int SD = jb.getInteger("sceneId");


                            if ("成功".equals(msg)) {
                              Startscen(SD,ST);
                            }else{
                                tv.setClickable(false);
                                HttpConnection.toastLog("服务器错误", AddCJActivity.this);
                            }
                        } else {
                            tv.setClickable(true);
                            HttpConnection.toastLog("服务器错误", AddCJActivity.this);

                        }
                    }

                });


    }


    public void Startscen(final int sceneId, final int ScenType) {
        AlertDialog.Builder builder = new AlertDialog.Builder(AddCJActivity.this);

        builder.setMessage("场景添加成功，是否立即启用该场景？");

        builder.setTitle("提示");

        builder.setPositiveButton("是", new Dialog.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {
                CJutil cj2 = new CJutil();
                cj2.sceneId = sceneId;
                cj2.sceneType = ScenType;
                String j = JSON.toJSONString(cj2);
                j = AESUtil.encrypt(j);
                HttpUtils httpUtils = new HttpUtils();
                RequestParams params = new RequestParams();
                params.setHeader("Content-Type", "application/json");
                try {
                    params.setBodyEntity(new StringEntity(j, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                httpUtils.send(HttpRequest.HttpMethod.POST, HttpConnection.startupScene, params,
                        new RequestCallBack<String>() {

                            @Override
                            public void onFailure(HttpException arg0, String arg1) {
                                ToastUtils.showToast(AddCJActivity.this,"网络异常");
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> arg0) {
                                if (arg0.result != null && !("".equals(arg0.result))) {
                                    arg0.result = AESUtil.decrypt(arg0.result);
                                    JSONObject jb = JSONObject.parseObject(arg0.result);
                                    JSONArray ja = jb.getJSONArray("sceneList");
                                    String msg = jb.getString("msg");

                                    if ("成功".equals(msg)) {
                                        m.ScenId=-1;
                                        AddCJActivity.this.finish();
                                    }else{
                                        HttpConnection.toastLog("服务器错误", AddCJActivity.this);
                                    }
                                } else {
                                    HttpConnection.toastLog("服务器错误", AddCJActivity.this);

                                }
                            }

                        });

            }});
        builder.setNegativeButton("否", new Dialog.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                m.ScenId=-1;
                AddCJActivity.this.finish();

            }
        });

        AlertDialog dialog3= builder.create();
        dialog3.setCanceledOnTouchOutside(false);
        dialog3.show();

}}